package com.example.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.example.config.RsaProperties;
import com.example.dto.dept.Dept;
import com.example.dto.user.User;
import com.example.dto.user.UserCriteria;
import com.example.server.DeptServer;
import com.example.server.UserServer;
import com.example.util.RsaUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Api(tags = "系统：用户管理")
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserServer userServer;
    @Autowired
    private DeptServer deptServer;

    @ApiOperation("增加用户")
    @PostMapping
    public ResponseEntity<Object> createUser(@Validated @RequestBody User resources) throws Exception {
        resources.setPassword(RsaUtils.encryptByPublicKey(RsaProperties.publicKey, "123456"));
        userServer.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @ApiOperation("删除用户")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody  Set<Long> ids){
        userServer.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改用户")
    @PutMapping
    public ResponseEntity<Object> updateUser(@RequestBody User resources) throws Exception {
        userServer.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @ApiOperation("查找用户")
    @GetMapping
    public ResponseEntity<Object> queryUser(UserCriteria criteria){
        if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
            criteria.getDeptIds().add(criteria.getDeptId());
            // 先查找是否存在子节点
            List<Dept> data = deptServer.findByPid(criteria.getDeptId());
            // 然后把子节点的ID都加入到集合中
            criteria.getDeptIds().addAll(deptServer.getDeptChildren(data));
        }
        if (!CollectionUtils.isEmpty(criteria.getDeptIds())){
            if(!CollectionUtil.isEmpty(criteria.getDeptIds())){
                return new ResponseEntity<>(userServer.list(criteria),HttpStatus.OK);
            }
        } else {
            return new ResponseEntity<>(userServer.list(criteria),HttpStatus.OK);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
